package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("common")
public class CommonController {

    @Value("${reggie.path}")
    private String basePath;

    @PostMapping("upload")
    public R upload(MultipartFile file) throws IOException {

        //获取文件名
        String filename = file.getOriginalFilename();
        File file1 = new File(basePath);
        if (!file1.exists()){
            file1.mkdirs();
        }
        String s = UUID.randomUUID().toString();
        String fileNowName = filename.substring(filename.lastIndexOf("."));
        fileNowName =  s + fileNowName;
        file.transferTo(new File(basePath+fileNowName));
        return R.success(fileNowName);
    }


    @GetMapping("download")
    public void download(String name, HttpServletResponse response) throws Exception {
        FileInputStream is = new FileInputStream(new File(basePath+name));
        ServletOutputStream os = response.getOutputStream();
        IOUtils.copy(is,os);
    }
}
